package y_2025.m11.d12;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个 CountDownLatch 实例，参数为需要等待的线程数量
        CountDownLatch latch = new CountDownLatch(3);

        // 创建三个工作线程 - 显式指定泛型类型
        List<Thread> workers = Stream
                .generate(() -> new WorkerThread("Worker", latch))
                .limit(3)
                .collect(toList());

        // 启动所有线程 - 使用方法引用
        workers.forEach(Thread::start);

        // 等待所有工作线程完成操作
        latch.await();

        // 所有工作线程完成后执行的代码
        System.out.println("工作线程执行完成");
    }

    static class WorkerThread extends Thread {
        private final CountDownLatch latch;

        public WorkerThread(String name, CountDownLatch latch) {
            super(name);
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                // 模拟工作线程执行任务
                System.out.println(getName() + " is performing task...");
                // 模拟任务执行时间
                Thread.sleep(2000);

                System.out.println(getName() + " has finished its task.");

                // 任务完成后调用 countDown() 方法，减少计数器
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}